package com.zhouheng.common.security;

import com.zhouheng.module.dao.SysUserMapper;
import com.zhouheng.module.entity.SysUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import static java.util.Collections.emptyList;


/**
 * 实现自定义用户认证接口
 *
 * @author 周恒
 * @date 20180831 16:02:20
 * @since v1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private SysUserMapper sysUserMapper;

    public UserDetailsServiceImpl(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 获取数据库用户信息，并封装成UserDetails.User返回
     * 这里只是验证有没有这个用户，验证密码和设置权限在CustomAuthenticationProvider中
     *
     * @param username 用户名
     * @author 周恒
     * @date 20200120 16:41:45
     * @since v1.0
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.findByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException(username);
        }
        return new org.springframework.security.core.userdetails.User(sysUser.getUsername(), sysUser.getPassword(), emptyList());
    }

}
